package com.coder.action;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Date;
import java.util.Map;

import org.apache.log4j.Logger;
import org.apache.struts2.interceptor.SessionAware;

import net.sf.json.JSONObject;

import com.opensymphony.xwork2.ActionSupport;
import com.coder.model.User;
import com.coder.service.UserService;
import com.coder.utils.DateUtilMy;

public class UserAction extends ActionSupport  implements SessionAware{

	private static final long serialVersionUID = 1L;

	private User user;
	private UserService userService;
	protected JSONObject jsonObject = new JSONObject();
	
    //Struts2中Map类型的session
    private Map<String, Object> session;
    private String securityCode;
    private String validateCode;
    private String newPs;
    private String message;
	private static final Logger LOGGER = Logger.getLogger(UserAction.class);
	
	/**用户退出操作*/
	public String quit(){
		
		session.remove("currUser");
		return SUCCESS;
	}
	
	/**更新用户，使用saveOrUpdate方法*/
	public String updateUser(){
		
		if(!validateUser(user)){
			message = ERROR;
			return ERROR;
		}
		
		if(!newPs.equals("")){
			LOGGER.info("用户在修改密码");
			user.setPassword(newPs); 
		}
		
		System.out.println("update ###############user");
		
		try{
			userService.saveOrUpdateUser(user);
		}catch(Exception e){
			e.printStackTrace();
			return ERROR;
		}
		
		//更新session中的用户
		User userInSession = null;
		try {
			userInSession = user.clone();
		} catch (CloneNotSupportedException e) {
			e.printStackTrace();
		}
		session.put("currUser", userInSession);
		message = SUCCESS;
		return SUCCESS;
	}
	
	/**注册用户*/
	public String createUser(){
		
		if(!validateUser(user)){
			message = ERROR;
			return ERROR;
		}
		
		userService.saveOrUpdateUser(user);
		message = SUCCESS;
		return SUCCESS;
	}
	
	/**验证用户是否存在,用于在提交表单之前验证，不进行页面跳转*/
	public String validateUserInfo(){
		
		boolean exist = userService.checkUserExist(user);
		if(!exist){
			LOGGER.info("登录成功");
			message = "unexist";
		}else{
			message = "exist";
		}
		return SUCCESS;
	}
	
	/**用户登录并提交表单，进行页面跳转*/
	public String userLogin(){
		
		boolean exist = userService.checkUserExist(user);
		
		if(!exist){
			return ERROR;
		}
		
		//不包含@表示用用户名登录的，因为都是通过username接收的参数
		//所以下面都是user.getUsername
		if(user.getUsername().indexOf("@")==-1){
			user = userService.getUserByName(user.getUsername());
		}else{
			user = userService.getUserByEmail(user.getUsername());
		}
		
		User userInSession = null;
		try {
			userInSession = user.clone();
		} catch (CloneNotSupportedException e) {
			e.printStackTrace();
		}
		session.put("currUser", userInSession);
		
		return SUCCESS;
	}
	
	/**检查密码是否正确，在用户中心页面*/
	public String checkPs(){
		
		user.setUsername(((User)session.get("currUser")).getUsername());
		
		System.out.println(user.getUsername());
		
		boolean exist = userService.checkUserExist(user);
		if(exist){
			LOGGER.info("用户输入密码正确");
			message = "right";
		}else{
			message = "wrong";
		}
		
		return SUCCESS;
	}
	
	
	/**修改密码*/
	public String chanPw(){
		
		String newPw = user.getPassword();
		
		try {
			user = userService.getUserByEmail(user.getEmail().trim());
		} catch (Exception e) {
			message = ERROR;
			e.printStackTrace();
		}
		
		user.setPassword(newPw);
		
		message = SUCCESS;
		try{
			userService.updateUser(user); 
		}catch(Exception e){
			message = ERROR;
			e.printStackTrace();
		}
		return SUCCESS;
	}
	
	//用户点击邮件中的修改密码链接时，转到这个方法，
	//验证用户的邮箱移机验证码有没有问题
	public String revChanPwEmail(){
		
		try {
			user = userService.getUserByEmail(user.getEmail().trim());
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		if(user == null || !user.getValidCode().equals(validateCode)){
			message = "邮件或验证码有误，请确认信息，或者重新申请";
			return ERROR;
		}
		
		double hours = DateUtilMy.getHoursBetweenDate(new Date(),user.getValidDate());
		
		System.out.println(hours);
		
		if(hours>12){
			message = "验证码已经过期，请重新申请";
			return ERROR;
		}
		
		return SUCCESS;
	}
	
	//验证邮件是否存在
	public String checkEmailExist(){
		try {
			user = userService.getUserByEmail(user.getEmail().trim());
		} catch (Exception e) {
			e.printStackTrace();
		}
		if(user == null){
			jsonObject.put("isExist", false);
		}else{
			jsonObject.put("isExist", true);
		}
		
		return SUCCESS;
	}
	
	//验证用户名是否存在
	public String checkUserNameExist(){

		try {
			user = userService.getUserByName(URLDecoder.decode(user.getUsername(), "utf-8"));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		
		if(user == null){
			jsonObject.put("isExist", false);
		}else{
			jsonObject.put("isExist", true);
		}
		return SUCCESS;
	}
	
	//为用户发送修改密码链接地址的邮件
	public String findPwByEmail(){
		
		message = SUCCESS;
		try{
			userService.updateAndSendEmail4FindPw(user.getEmail().trim());
		}catch(Exception e){
			message = ERROR;
			e.printStackTrace();
		}
		return SUCCESS;
	}
	
	//检查验证码
	public String checkSecureCode(){

	    String serverCode = (String)session.get("SESSION_SECURITY_CODE");
        if(!serverCode.equals(securityCode)){
        	jsonObject.put("isCorrect", false);
        }else{
        	jsonObject.put("isCorrect", true);
        }
        return SUCCESS;
	}
	
	
	private boolean validateUser(User user){
		
		if(user.getUsername().equals("")){
			LOGGER.error("the user name is null");
			return false;
		}
		if(user.getPassword().equals("")){
			LOGGER.error("password is null");
			return false;
		}
		return true;
	}
	
	public User getUser() {
		return user;
	}
	public void setUser(User user) {
		this.user = user;
	}

	public JSONObject getJsonObject() {
		return jsonObject;
	}

	public void setJsonObject(JSONObject jsonObject) {
		this.jsonObject = jsonObject;
	}

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public Map<String, Object> getSession() {
		return session;
	}

	public void setSession(Map<String, Object> session) {
		this.session = session;
	}

	public String getSecurityCode() {
		return securityCode;
	}

	public void setSecurityCode(String securityCode) {
		this.securityCode = securityCode;
	}

	public String getValidateCode() {
		return validateCode;
	}

	public void setValidateCode(String validateCode) {
		this.validateCode = validateCode;
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public String getNewPs() {
		return newPs;
	}

	public void setNewPs(String newPs) {
		this.newPs = newPs;
	}
}
